package com.building.hcrm.common;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.building.hcrm.wcf.UserServiceProxy;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Environment;

public class ComFunc {

	
	private static Long _timeDifference = Long.MAX_VALUE;
	/**
	 * 计算本地与服务端的时间差值并获取时间
	 * @param context
	 * @return 校正差值之后的时间
	 * @throws Exception
	 */
	public static Date getRealTime(Context context) throws Exception {
		Date dNow = null;// 获取本地当前时间
		if (_timeDifference == Long.MAX_VALUE) {
			// 获取服务端时间
			Date dateServer = UserServiceProxy.getInstance(context)
					.GetServerTime();
			// 获取本地当前时间
			dNow = new Date();
			// 比较保存差值,以后上传服务器的时间,以---当前时间+差值为准
			_timeDifference = dateServer.getTime() - dNow.getTime();// 获取差值
		} else {
			// 获取本地当前时间
			dNow = new Date();
		}
		return new Date(dNow.getTime() + _timeDifference);
	}
	
	/**
	 * 拼装时间格式
	 * 
	 * @param strDate
	 * @return
	 */
	public static String GetStringByDate(Date date, String formatString) {

		String DateString = "";
		if (date != null)
			DateString = new SimpleDateFormat(formatString, Locale.getDefault())
					.format(date);
		return DateString;
	}

	/**
	 * String→时间
	 * 
	 * @param strDate
	 * @return
	 */
	public static Date GetDateByString(String dateString, String formatString) {

		Date d = new Date(1,1,1);// 默认值
		try {
			if (dateString != null && dateString.length() > 0)
				d = new SimpleDateFormat(formatString, Locale.getDefault())
						.parse(dateString);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return d;
	}

	/**
	 * 获取IP
	 * 
	 * @return
	 */
	public static String getLocalIpAddress() {
		try {
			for (Enumeration<NetworkInterface> en = NetworkInterface
					.getNetworkInterfaces(); en.hasMoreElements();) {
				NetworkInterface intf = en.nextElement();
				for (Enumeration<InetAddress> enumIpAddr = intf
						.getInetAddresses(); enumIpAddr.hasMoreElements();) {
					InetAddress inetAddress = enumIpAddr.nextElement();
					if (!inetAddress.isLoopbackAddress()
							&& inetAddress.getClass()
									.equals(Inet4Address.class)) {
						return inetAddress.getHostAddress().toString();
					}
				}
			}
		} catch (SocketException ex) {
		}
		return null;
	}

	/**
	 * 在android手机上创建路径(必须一级一级创建)
	 * 
	 * @param path
	 */
	public static void createPath(String path) {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdir();
		}
	}


	/**
	 * SD卡是否存在
	 * 
	 * @return
	 */
	public static boolean ExistSDCard() {
		if (Environment.getExternalStorageState().equals(
				Environment.MEDIA_MOUNTED)) {
			return true;
		} else
			return false;
	}

	/**
	 * 获取外部存储根路径
	 * 
	 * @return
	 */
	public static File getStorageDirectory() {

		return Environment.getExternalStorageDirectory();
	}

	/**
	 * InputStream转String
	 * 
	 * @param is
	 * @return
	 * @throws IOException
	 */
	public static String inputStream2String(InputStream is) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		int i = -1;
		while ((i = is.read()) != -1) {
			baos.write(i);
		}
		return baos.toString();
	}

	public static String getExceptionMessage(Throwable e) {
		if (e == null) {
			return "Exception对象为空..";
		}
		String separator = System.getProperty("line.separator");

		StringBuilder str = new StringBuilder("错误消息：");
		str.append("\t");
		str.append(e.getMessage());
		str.append(separator);

		str.append("堆栈信息：");
		for (StackTraceElement element : e.getStackTrace()) {
			str.append("\t");
			str.append(element.toString());
			str.append(separator);
		}

		return str.toString();
	}

	/**
	 * 将时间格式转换为Json格式 如:"\/Date(1368028800000)\/"
	 * 
	 * @param dtDate
	 * @return 如:"\/Date(1368028800000)\/"
	 */
	public static String DateToJsonFormat(Date dtDate) {
		StringBuilder sb = new StringBuilder();
		sb.append("/Date(");
		// TODO:getTime默认是以GMT为准，所以这里合并上时区偏移量
		long lTmp = dtDate.getTime() - (dtDate.getTimezoneOffset() * 60000);
		sb.append(lTmp);
		sb.append(")/");
		return sb.toString();
	}

	/**
	 * 邮件地址验证
	 * 
	 * @param email
	 * @return
	 */
	public static boolean isEmail(String email) {
		String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
		Pattern p = Pattern.compile(str);
		Matcher m = p.matcher(email);
		return m.matches();
	}

	/**
	 * 手机号码验证
	 * 
	 * @param mobiles
	 * @return
	 */
	public static boolean isMobileNO(String mobiles) {
		Pattern p = Pattern
				.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}

}
